import Vue from 'vue'
import App from './App'
import store from './store'
import mTool from './common/tools.js'
import * as apis from './apis/index.js'
import mRouter from './common/router.js'
import mRoutesConfig from './config/routes.config.js'
import GraceChecker from "./common/graceChecker.js"
import FormRuleConfig from './config/formRule.config.js'


import barTitle from '@/components/basics/bar-title';
import barSearch from '@/components/basics/bar-search';
Vue.component('bar-title',barTitle)
Vue.component('bar-search',barSearch)



mRouter.beforeEach((navType, to) => {
	let token = uni.getStorageSync('Token')
	
	if (to.route === undefined) {
		throw ("路由钩子函数中没有找到to.route对象，路由信息:" + JSON.stringify(to));
	}
	// 过滤需要权限的页面
	if (to.route.requiresAuth) {
		if (token.username) {
			// 已经登录
			uni[navType]({
				url: mTool.objParseUrlAndParam(to.route.path, to.query)
			})
		} else {
			// 登录成功后的重定向地址和参数
			let redirectUrl = mTool.objParseUrlAndParam(to.route.path, {
				...to.query
			})
			uni.setStorageSync('loginBefore', redirectUrl);
			// 没有登录 强制登录
			uni[navType]({
				url: mTool.objParseUrlAndParam(mRoutesConfig.login.path)
			})
		}
	} else {
		uni[navType]({
			url: mTool.objParseUrlAndParam(to.route.path, to.query)
		})
	}
})



const jumpPages = (pageName, option={}, routerType='push') => {
	if (mRoutesConfig[pageName] === undefined)
		throw (pageName +"路由不存在，请检查你的路由配置");
	console.log(pageName, routerType, mRoutesConfig[pageName]);
	mRouter[routerType]({
		route: mRoutesConfig[pageName],
		query: option
	});
}
const backPage = () => {
	uni.navigateBack({
		delta: 1,
		fail: (e) => {
			uni.redirectTo({
				url: '/pages/app/index'
			});
		}
	});
}
			
Vue.config.productionTip = false
Vue.prototype.$fire = new Vue();
Vue.prototype.$store = store;
Vue.prototype.$mTool = mTool;
Vue.prototype.$jumpPages = jumpPages;
Vue.prototype.$backPage = backPage;

Vue.prototype.$apis = apis;
Vue.prototype.$graceChecker = GraceChecker;
Vue.prototype.$formRuleConfig = FormRuleConfig;

App.mpType = 'app'

const app = new Vue({
	store,
    ...App
})
app.$mount()
